<?php
namespace Dybasedev\Dataman;

use PDO;
use Dybasedev\Dataman\Schema\MySqlBuilder;
use Doctrine\DBAL\Driver\PDOMySql\Driver as DoctrineDriver;
use Illuminate\Database\Query\Grammars\MySqlGrammar as QueryGrammar;
use Dybasedev\Dataman\Schema\Grammars\MySqlGrammar as SchemaGrammar;
use Illuminate\Database\Query\Processors\MySqlProcessor;


class MySqlConnection extends Connection {

    /**
     * Get a schema builder instance for the connection.
     *
     * @return \Dybasedev\Dataman\Schema\MySqlBuilder
     */
    public function getSchemaBuilder()
    {
        if (is_null($this->schemaGrammar)) { $this->useDefaultSchemaGrammar(); }

        return new MySqlBuilder($this);
    }

    /**
     * Get the default query grammar instance.
     *
     * @return \Dybasedev\Dataman\Query\Grammars\MySqlGrammar
     */
    protected function getDefaultQueryGrammar()
    {
        return $this->withTablePrefix(new QueryGrammar);
    }

    /**
     * Get the default schema grammar instance.
     *
     * @return \Dybasedev\Dataman\Schema\Grammars\MySqlGrammar
     */
    protected function getDefaultSchemaGrammar()
    {
        return $this->withTablePrefix(new SchemaGrammar);
    }

    /**
     * Get the default post processor instance.
     *
     * @return \Dybasedev\Dataman\Query\Processors\Processor
     */
    protected function getDefaultPostProcessor()
    {
        return new MySqlProcessor;
    }

    /**
     * Get the Doctrine DBAL driver.
     *
     * @return \Doctrine\DBAL\Driver\PDOMySql\Driver
     */
    protected function getDoctrineDriver()
    {
        return new DoctrineDriver;
    }

    /**
     * Show all databases
     * 
     * @return array
     */
    public function getDatabases()
    {
        $fetchMode = $this->getFetchMode();

        $this->setFetchMode(PDO::FETCH_COLUMN);

        $result = $this->select('show databases;');

        $this->setFetchMode($fetchMode);

        return $result;
    }

    /**
     * Show all data tables
     * 
     * @return array
     */
    public function getTables()
    {
        $fetchMode = $this->getFetchMode();

        $this->setFetchMode(PDO::FETCH_COLUMN);

        $result = $this->select('show tables;');

        $this->setFetchMode($fetchMode);

        return $result;
    }

    /**
     * Switch database
     * 
     * @param  string   $database   Database name
     * @return $this
     */
    public function database($database, $prefix = null)
    {
        $sth = $this->getPdo()->exec("use `$database`;");

        $this->setDatabaseName($database);

        if (!is_null($prefix)) {
            $this->setTablePrefix($prefix);
        }

        return $this;
    }

}
